<?php
class Model{
	var $controller;
	var $table=null;
	var $data=array();
	function __construct($controller){
		$this->controller=$controller;
		$this->table=$GLOBALS["CONFIG"]["db"]["prefix"].strtolower($this->name).'s';
	}
	function fetch_one($q_resource){
		$map = array();
		$numFields = mysql_num_fields($q_resource);
		$index = 0;
		$j = 0;
		while ($j < $numFields) {
			$column = mysql_fetch_field($q_resource,$j);
			if (!empty($column->table)) {
				$map[$index++] = array($column->table, $column->name);
			} else {
				$map[$index++] = array(0, $column->name);
			}
			$j++;
		}
		if ($row = mysql_fetch_row($q_resource)) {
			$resultRow = array();
			$i = 0;
			foreach ($row as $index => $field) {
				list($table, $column) = $map[$index];
				$resultRow[$table][$column] = $row[$index];
				$i++;
			}
			return $resultRow;
		}
		return false;
	}
	function fetch_all($q_resource){
		$map = array();
		$numFields = mysql_num_fields($q_resource);
		$index = 0;
		$j = 0;
		$result=false;
		while ($j < $numFields) {
			$column = mysql_fetch_field($q_resource,$j);
			if (!empty($column->table)) {
				$map[$index++] = array($column->table, $column->name);
			} else {
				$map[$index++] = array(0, $column->name);
			}
			$j++;
		}
		$result=array();
		while ($row = mysql_fetch_row($q_resource)) {
			$resultRow = array();
			$i = 0;
			foreach ($row as $index => $field) {
				list($table, $column) = $map[$index];
				$resultRow[$table][$column] = $row[$index];
				$i++;
			}
			$result[]= $resultRow;
		}
		return $result;
	}
	function findById($id){
		return $this->find('first',array('conditions'=>array('id'=>$id)));
	}
	function findAllByUserId($uid){
		return $this->find('all',array('conditions'=>array('user_id'=>$uid)));
	}
	function select_sql($name,$conf=null){
		$fields=$conf['fields'];
		$conditions=$conf['conditions'];
		$field_names='';
		$table='`'.$GLOBALS["CONFIG"]["db"]["prefix"].strtolower($name).'s` AS `'.$name.'` ';
		if($this->name==$name&&is_array($this->belongsTo)){
			foreach($this->belongsTo as $beloning){
				$table.=' LEFT JOIN `'.$GLOBALS["CONFIG"]["db"]["prefix"].strtolower($beloning).'s`';
				$table.=' AS `'.$beloning.'` ON (`'.$beloning.'`.`id` = `'.$this->name.'`.`'.strtolower($beloning).'_id`)';
			}
		}
		if(is_array($fields)){
			foreach($fields as $field_name){
				if($field_names!=''){
					$field_names.=' , ';
				}
				if(substr_count($field_name,'.')>0){
					$field_names.=' '.$field_name.' ';
				}else{
					$field_names.='`'.$name.'`.`'.$field_name.'`';
				}
			}
		}else{
			$field_names='*';
		}
		$sql='SELECT '.$field_names.' FROM '.$table;
		$sql_condition='';
		if(is_array($conditions)){
			foreach($conditions as $key => $value){
				if($sql_condition!=''){
					$sql_condition.=' AND ';
				}
				if(is_array($value)){
					$tmp='(';
					foreach($value as $k=>$v){
						if($tmp!='('){
							$tmp.=', ';
						}
						$tmp.='\''.$v.'\'';
					}
					$tmp.=')';
					$value=$tmp;

				}elseif(!is_int($key)){
					$value='\''.$value.'\'';
				}
				if(is_int($key)){
					$sql_condition.=' '.$value.' ';
				}elseif(substr_count($key,'<')+substr_count($key,'>')>0){
					if(substr_count($key,'.')>0){
						$sql_condition.=' '.$key.' '.$value;
					}else{
						$sql_condition.='`'.$name.'`.'.$key.' '.$value;
					}
				}else{
					if(substr_count($key,'.')>0){
						$sql_condition.=' '.$key.' = '.$value;
					}else{
						$sql_condition.='`'.$name.'`.`'.$key.'`='.$value;
					}
				}
			}
		}
		if($sql_condition!=''){
			$sql.=' WHERE '.$sql_condition;
		}
		if(is_array($conf['group'])){
			$sql.=' GROUP BY ';
			$i=0;
			foreach($conf['group'] as $k=>$v){
				if($i)
					$sql.=',';
				$sql.='`'.$v.'` ';
				$i++;
			}
		}
		if(is_array($conf['order'])){
			$sql.=' ORDER BY ';
			$i=0;
			foreach($conf['order'] as $k=>$v){
				if($i)
					$sql.=',';
				$sql.=$v.' ';
				$i++;
			}
		}
		return $sql;
	}
	function find($conditions = null, $fields = array(), $order = null, $recursive = null){
		if($this->table){
			$sql=$this->select_sql($this->name,$fields);
			$q_resource=mysql_query($sql);
			if (!$q_resource) {
				$message  = 'Invalid query: ' . mysql_error() . "<br>";
				$message .= 'Whole query: ' . $sql;
				throw new Exception($message);
			}
			switch($conditions){
				case 'all':
					$data=$this->fetch_all($q_resource);
					mysql_free_result($q_resource);
					if(is_array($this->hasMany)){
						$ids=array();
						foreach($this->hasMany as $beloning){
							foreach($data as $key=>$value){
								$sql=$this->select_sql($beloning,array('conditions'=>array(strtolower($this->name).'_id'=>$value[$this->name]['id'])));
								$q_resource=mysql_query($sql);
								if (!$q_resource) {
									$message  = 'Invalid query: ' . mysql_error() . "<br>";
									$message .= 'Whole query: ' . $sql;
									throw new Exception($message);
								}
								$data[$key]=array_merge($value,array($beloning=>$this->fetch_all($q_resource)));
							}
						}
					}
					return $data;
				case 'first':
					$data=$this->fetch_one($q_resource);
					mysql_free_result($q_resource);
					if(is_array($this->hasMany)){
						$ids=array();
						foreach($this->hasMany as $beloning){
							$sql=$this->select_sql($beloning,array('conditions'=>array(strtolower($this->name).'_id'=>$data[$this->name]['id'])));
							$q_resource=mysql_query($sql);
							if (!$q_resource) {
								$message  = 'Invalid query: ' . mysql_error() . "<br>";
								$message .= 'Whole query: ' . $sql;
								throw new Exception($message);
							}
							$data=array_merge($data,array($beloning=>$this->fetch_all($q_resource)));
						}
					}
					return $data;
				case 'count':
					$num=mysql_num_rows($q_resource);
					mysql_free_result($q_resource);
					return $num;
				default:
					throw new Exception('Unhandled Model::find condition '.$conditions);
			}
			return null;
		}
	}
	function set($a,$b=null){
		if(is_string($a)&&is_string($b)){
			$this->data[$this->name][$a]=$b;
			return true;
		}elseif(is_array($a)){
			$this->data=array_merge($a,$this->data);
			return true;
		}
		return false;
	}
	function validates(){
		return true;
	}
	function save($data = null, $validate = true, $fieldList = array()){
		if(isset($this->id)){
			$sql='UPDATE `'.$this->table.'` SET ';
			if(is_array($data)){
				$data=array_merge($data,$this->data);
			}else{
				$data=$this->data;
			}
			$data_string='';
			foreach($data[$this->name] as $field => $value){
				if($data_string!=''){
					$data_string.=',';
				}
				$data_string.='`'.$field.'`=\''.$value.'\'';
			}
			$sql.=$data_string.' WHERE `id` = \''.$this->id.'\'';
			unset($this->id);
			unset($this->data);
			$this->data=array();
			return mysql_query($sql);
		}else{
			$sql='INSERT INTO `'.$this->table.'` ';
			if(is_array($data)){
				$data=array_merge($data,$this->data);
			}else{
				$data=$this->data;
			}
			$data_string='(';
			$field_string='(';
			foreach($data[$this->name] as $field => $value){
				if($data_string!='('){
					$data_string.=',';
				}
				if($field_string!='('){
					$field_string.=',';
				}
				$field_string.='`'.$field.'`';
				$data_string.='\''.$value.'\'';
			}
			$data_string.=')';
			$field_string.=')';
			$sql.=$field_string.' VALUES '.$data_string;
			unset($this->id);
			unset($this->data);
			return mysql_query($sql);
		}
	}
}